package com.invengo.testrfid.mvp.presenter;

import android.app.Application;
import android.widget.TextView;

import com.invengo.testrfid.app.dao.QueryManager;
import com.invengo.testrfid.app.dao.RfidCageBind;
import com.invengo.testrfid.app.entity.MessageEntity;
import com.invengo.testrfid.app.entity.ReadTagEntity;
import com.invengo.testrfid.app.proxy.ProxyNetWorker;
import com.invengo.testrfid.app.proxy.ProxyReadTag;
import com.invengo.testrfid.app.utils.ByteConvertUtils;
import com.invengo.testrfid.app.utils.Constant;
import com.invengo.testrfid.app.utils.GsonUtils;
import com.invengo.testrfid.app.utils.MyLogUtils;
import com.invengo.testrfid.app.utils.SoundPlayUtils;
import com.invengo.testrfid.mvp.contract.UpdateCageContract;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;

import javax.inject.Inject;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;


@ActivityScope
public class UpdateCagePresenter extends BasePresenter<UpdateCageContract.Model, UpdateCageContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    QueryManager queryManager;
    private RfidCageBind curRfidCageBind;
    /**
     * 标签1
     */
    private TextView textViewTid1;

    /**
     * 标签2
     */
    private TextView textViewTid2;

    @Inject
    public UpdateCagePresenter(UpdateCageContract.Model model, UpdateCageContract.View rootView) {
        super(model, rootView);

        this.queryManager = QueryManager.getManager();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
        this.queryManager = null;
    }


    public void readTagTid(TextView textView1, TextView text2) {

        this.textViewTid1 = textView1;
        this.textViewTid2 = text2;

        ProxyReadTag.getInstance().readTagAllData(new ProxyReadTag.ReadTagAllDataCallbac() {
            @Override
            public void onReadTagSuccess(ReadTagEntity readTagEntity) {

                handTid(readTagEntity.getTid(),readTagEntity.getEpc());
            }

            @Override
            public void onReadTagFailed(String msg) {

                if (mRootView != null)
                    mRootView.showMessage(msg);
            }
        });
    }

    /**
     * 处理读取结果
     *
     * @param tid
     */
    private void handTid(String tid,String epc) {


        mRootView.showMessage(epc);
        String tid1 = textViewTid1.getText().toString();
        String tid2 = textViewTid2.getText().toString();

        MyLogUtils.log(Constant.ValueOfTag_ADD,epc,4);

        if (!tid1.equals("Tid1") && !tid2.equals("Tid2")) {

            mRootView.showMessage("如要修改某个TID，请点击该标签后边的重置按钮");
        }
        if (tid1.equals("Tid1") && tid2.equals("Tid2")) {

            RfidCageBind rfidCageBind = queryManager.getRfidCageQuery().queryDataByTid(tid);
            if (rfidCageBind != null) {

                curRfidCageBind = rfidCageBind;
                String[] split = rfidCageBind.getTagId().split(Constant.ValueOfSpare);

                mRootView.initCageNo(rfidCageBind.getCageId());
                mRootView.initTid(split[0],"");
                mRootView.initTidSecond(split[1],"");

            } else {
                mRootView.showMessage("未查询到该 TID 的绑定关系");
            }
            return;
        }

        // 该标签已绑定，显示失败信息
        RfidCageBind rfidCageBind = queryManager.getRfidCageQuery().queryDataByTid(tid);
        if (rfidCageBind != null) {

            SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_FAILED, 1);
            mRootView.showMessage("该标签已绑定，请更换标签！");
            return;
        }


        if (textViewTid1.getText().toString().contains(tid)) {
            mRootView.initTid(tid,epc);
            return;
        }

        if (textViewTid2.getText().toString().contains(tid)) {
            mRootView.initTidSecond(tid,epc);
            return;
        }

        if (textViewTid1.getText().toString().contains("Tid1")
                || textViewTid1.getText().toString().equals(tid)) {

            textViewTid1.setText(tid);
            mRootView.initTid(tid,epc);
        } else if (textViewTid2.getText().toString().contains("Tid2")
                && !textViewTid1.getText().toString().contains(tid)) {

            MyLogUtils.log(Constant.ValueOfTag_ADD, tid + "___" + textViewTid1.getText().toString(), 1);
            textViewTid2.setText(tid);
            mRootView.initTidSecond(tid,epc);
        } else {

            // 先不进行焦点的提示
//            mRootView.requestFocus();
        }

    }

    /**
     * 更具笼车编号来查询绑定信息
     *
     * @param cageNo
     */
    public void searchCageByNo(String cageNo) {

        RfidCageBind rfidCageBind = queryManager.getRfidCageQuery().queryDataByCageNo(cageNo);

        if (rfidCageBind != null) {

            curRfidCageBind = rfidCageBind;
            String[] split = rfidCageBind.getTagId().split(Constant.ValueOfSpare);
            mRootView.initTid(split[0],"");
            mRootView.initTidSecond(split[1],"");
            mRootView.initCageNo(rfidCageBind.getCageId());
        } else {
            mRootView.showMessage("未查询到该编号的绑定信息");
        }
    }

    public void stopReadTag() {

        ProxyReadTag.getInstance().stopRead(new ProxyReadTag.StopReadCallback() {

            @Override
            public void onStopSuccess() {

            }

            @Override
            public void onStopFailed() {

                mRootView.showMessage("停止读取标签操作失败，请重试");
            }
        });
    }


    /**
     * 根据id来查询绑定关系
     *
     * @param tid
     */
    public void updateTheBindByTid(String tid, String tid2, String cageNo) {

        if (tid.length() == 0 || cageNo.length() == 0 || tid.equals("tid")) {

            saveFailed("TID数据或者集装箱编号不可以为空！");
            return;
        }

        RfidCageBind rfidCageBind1 = queryManager.getRfidCageQuery().queryDataByCageNo(cageNo);
        if(rfidCageBind1 != null){

            mRootView.showMessage("该集装箱编号已绑定，请更换");
            return;
        }

        RfidCageBind rfidCageBind = queryManager.getRfidCageQuery().queryDataByTid(tid + Constant.ValueOfSpare + tid2);
        if (rfidCageBind != null) {

            rfidCageBind.setCageId(cageNo);
            rfidCageBind.setIsBind(false);
            queryManager.getRfidCageQuery().update(rfidCageBind);
            mRootView.clearCageNo();
        } else {

            mRootView.showMessage("未找到Tid对应的绑定信息");
        }

    }

    /**
     * 根据笼车号来更新笼车绑定关系
     *
     * @param tid
     * @param cageNo
     */
    public void updateTheBindByCageNo(String tid,String tid2, String cageNo) {

        if (tid.length() == 0 || cageNo.length() == 0 || tid.equals("Tid1") || tid2.equals("Tid2")) {
            saveFailed("TID数据或者集装箱编号不可以为空！");
            return;
        }

        RfidCageBind rfidCageBind = queryManager.getRfidCageQuery().queryDataByCageNo(cageNo);
        if(rfidCageBind != null){

            rfidCageBind.setTagId(tid+ Constant.ValueOfSpare+tid2);
            rfidCageBind.setIsBind(false);
            queryManager.getRfidCageQuery().update(rfidCageBind);
            mRootView.clearCageNo();
        }else {

            mRootView.showMessage("该集装箱编号未查询到绑定数据");
        }


        if(true){
            return;
        }

        String url = "http://" + Constant.byIp + "/api/CageInfo/CageSCUpdateByCodeName?tid=" + tid + "&codeName=京烟" + cageNo;
        ProxyNetWorker.getInstance().getServerData(url, new ProxyNetWorker.RequestCallback() {
            @Override
            public void onSuccess(String data) {

                MyLogUtils.log("test", "update_" + data, 4);
                MessageEntity messageEntity = (MessageEntity) GsonUtils.jsonToBean(data, MessageEntity.class);
                if (messageEntity.getStatus().equals("1")) {

                    mRootView.showMessage("更新成功");
                    SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_SUCCESS, 3);
                } else {
                    mRootView.showMessage(messageEntity.getInfo());
                }
            }

            @Override
            public void onFailed(String msg) {

                mRootView.showMessage("更新失败--" + msg);
                MyLogUtils.log("test", "update_" + msg, 4);
            }
        });

    }

    private void saveFailed(String message) {

        SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_FAILED, 0);
        mRootView.showMessage(message);
    }

    public void connectReader() {

        ProxyReadTag.getInstance().connectReader(new ProxyReadTag.ConnectReaderStatue() {
            @Override
            public void onConnectSuccess() {
//
//                mRootView.showMessage("读写器连接成功");
            }

            @Override
            public void onConnectFailed() {

//                mRootView.showMessage("读写器连接失败");
            }
        });
    }

    /**
     * 断开连接
     */
    public void disConnectReader() {

        ProxyReadTag.getInstance().disConnectReader(new ProxyReadTag.DisConnectReaderStatue() {
            @Override
            public void onDisConnectSuccess() {

            }

            @Override
            public void onDisConnectFailed() {

            }
        });
    }

    /**
     * 将数据写入标签
     */
    public void writeData(String data) {

        if(data.trim().length() == 0){
            mRootView.showMessage("集装箱编号不可以");
            return;
        }

        ProxyReadTag.getInstance().writeDataToEpc(ByteConvertUtils.strToByteArray(data), new ProxyReadTag.WriteTagEpcCallback() {
            @Override
            public void onWriteSuccess() {

                mRootView.showMessage("写入标签成功");
            }

            @Override
            public void onWriteFailed() {

                mRootView.showMessage("写入标签失败");
            }
        });
    }
}
